import { config } from "./config.js";

// 判断定位授权
function getSettingIsok () {
  wx.getSetting({
    success: (res) => {
      let authSetting = res.authSetting
      if (authSetting['scope.userLocation']) {
        // 已授权
        wx.showModal({
          title: '',
          content: '请在系统设置中打开定位服务',
          confirmText: '确定',
        })
      } else {
        wx.showModal({
          title: '您未开启地理位置授权',
          content: '你的位置信息将用于图片效果展示',
          success: res => {
            if (res.confirm) {
              wx.openSetting()
            }
          }
        })
      }
    }
  })
}

// 换取中文地址
function getLocationAdd (location, fn) {
  wx.showLoading({ title: "获取定位信息" })
  wx.$post(2, 'map/tencent/ws/geocoder/location', {
    key: config.mapKey,
    location,
  }, false, true).then((res) => {
    wx.hideLoading()
    if (res.message == 'Success' || res.status == 0) {
      fn(res)
      return
    }
    wx.showToast({ title: res.message, icon: 'none', duration: 2000, })
  })
}

// 获取当前经纬度
function comeLocation (fn) {
  wx.showLoading({ title: '', })
  wx.getLocation({
    success (res) {
      fn(res)
    }, fail (res) {
      wx.hideLoading()
      // 先检查系统中是否开启了定位服务权限，如开启了就去判断微信定位是否开启，再继续执行传入的fn函数
      getSettingIsok()
    },
  })
}

wx.$getSettingIsok = getSettingIsok;
wx.$comeLocation = comeLocation;
wx.$getLocationAdd = getLocationAdd;
